package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class MovementsService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private TodayBestService todayBestService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String savePublish(String textContent, String location // 文本,地区
            , String latitude, String longitude// 纬度,经度
            , MultipartFile[] multipartFile/* 图片 */) {

        // 查询用户信息
        User user = UserThreadLocal.get();

        // 获取全部图片的url
        List<String> picUrls = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            // 处理图片,返回结果,从返回结果中获取url
            PicUploadResult uploadResult = picUploadService.upload(file);
            picUrls.add(uploadResult.getName());
        }

        // 创建publish对象,封装数据
        Publish publish = new Publish();
        publish.setUserId(user.getId());// 设置用户id
        publish.setText(textContent);// 设置文本
        publish.setLocationName(location);// 设置位置
        publish.setLatitude(latitude); // 纬度
        publish.setLongitude(longitude);// 经度
        publish.setSeeType(1);// 设置为公开(1-公开，2-私密，3-部分可见，4-不给谁看)
        publish.setMedias(picUrls);// 设置publish中的图片

        // 储存后返回结果[true / false]
        return quanZiApi.savePublish(publish);
    }

    private PageResult queryPublishList(User user, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        Long userId = null;
        PageInfo<Publish> pageInfo = null;

        // 没有用户  查询推荐动态
        if (user == null){
            String key = "QUANZI_PUBLISH_RECOMMEND_" + UserThreadLocal.get().getId();
            String resultData = redisTemplate.opsForValue().get(key);// 返回数据

            if (StringUtils.isNotEmpty(resultData)) {
                String[] pIds = StringUtils.split(resultData, ",");
                // 获取开始和结束索引
                int startIndex = (page - 1) * pageSize;
                if(startIndex < pIds.length){
                    int endIndex = startIndex + pageSize - 1;
                    if (endIndex >= pIds.length) {
                        endIndex = pIds.length - 1;
                    }

                    List<Long> pidList = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pidList.add(Long.valueOf(pIds[i]));
                    }

                    List<Publish> publishList = quanZiApi.queryPublishByPids(pidList);
                    if (publishList.size() != 0) {
                        pageInfo = new PageInfo<>();
                        pageInfo.setRecords(publishList);
                    }
                }
            }
        }

        if (pageInfo == null) {
            if (user != null) {
                userId = user.getId();
            }
            // 查询动态列表
            pageInfo = quanZiApi.queryPublishList(userId, page, pageSize);
        }

        // 封装
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        pageResult.setCounts(0);
        pageResult.setPages(0);

        List<Publish> records = pageInfo.getRecords();

        // 如果没有查到动态[publish]记录则直接返回
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }

        pageResult.setItems(fillValueToMovements(records));
        return pageResult;
    }

    private List<Movements> fillValueToMovements(List<Publish> records) {
        User user = UserThreadLocal.get();
        // 封装对象集合
        List<Movements> movementsList = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();

            String toHexString = "";

            toHexString = record.getId().toHexString();
            movements.setId(toHexString);
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setUserId(record.getUserId());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            movementsList.add(movements);

        }

        // 获取id
        List<Long> userIds = new ArrayList<>();
        for (Movements movements : movementsList) {
            if (!userIds.contains(movements.getId())) {
                userIds.add(movements.getUserId());
            }
        }

        // 查询用户信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryList(queryWrapper);

        // 封装
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {

                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));
                    movements.setCommentCount(10); //TODO 评论数
                    movements.setDistance("1.2公里"); //TODO 距离

                    String likeKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
                    movements.setHasLiked(redisTemplate.hasKey(likeKey) ? 1 : 0); // 是否点赞（1是，0否）

                    String likeCount = redisTemplate.opsForValue().get("QUANZI_COMMENT_LIKE_" + movements.getId());
                    movements.setLikeCount(StringUtils.isEmpty(likeCount) ? 0 : Integer.parseInt(likeCount)); // 点赞数

                    String loveKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
                    movements.setHasLoved(redisTemplate.hasKey(loveKey) ? 1 : 0); // 是否喜欢（1是，0否）

                    String loveCount = redisTemplate.opsForValue().get("QUANZI_COMMENT_LOVE_" + movements.getId());
                    movements.setLoveCount(StringUtils.isEmpty(loveCount) ? 0 : Integer.parseInt(loveCount)); // 喜欢数
                    break;
                }
            }
        }
        return movementsList;
    }

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return queryPublishList(null, page, pageSize);
    }

    public PageResult queryUserPublishList(Integer page, Integer pageSize) {
        return queryPublishList(UserThreadLocal.get(), page, pageSize);
    }

    public Long likeComment(String publishId) {
        // 保存点赞,重复点赞会返回false
        User user = UserThreadLocal.get();
        boolean saveLikeComment = quanZiApi.saveLikeComment(user.getId(), publishId);
        if (!saveLikeComment) {
            return null;
        }

        Long likeCount = 1L;
        //保存点赞数到redis
        String key = "QUANZI_COMMENT_LIKE_" + publishId;

        if (!redisTemplate.hasKey(key)) {
            likeCount = quanZiApi.queryCommentCount(publishId, 1);
            likeCount = likeCount == 0L ? 1L : likeCount;
            redisTemplate.opsForValue().set(key, likeCount + "");
        } else {
            likeCount = redisTemplate.opsForValue().increment(key);
        }

        // 添加 用户对动态的点赞记录
        String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.opsForValue().set(userKey, "1");

        return likeCount;
    }

    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean removeComment = quanZiApi.removeComment(user.getId(), publishId, 1);
        if (!removeComment) {
            return null;
        }

        // 点赞数减一,返回的是减一之后的点赞数
        Long count = redisTemplate.opsForValue().decrement("QUANZI_COMMENT_LIKE_" + publishId);
        // 移除 用户对动态的点赞记录
        redisTemplate.delete("QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId);

        return count;
    }

    public Long loveComment(String publishId) {

        // 保存喜欢,重复会返回false
        User user = UserThreadLocal.get();
        boolean saveLoveComment = quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!saveLoveComment) {
            return null;
        }

        Long loveCount = 0L;
        //保存点赞数到redis
        String key = "QUANZI_COMMENT_LOVE_" + publishId;

        if (!redisTemplate.hasKey(key)) {
            loveCount = quanZiApi.queryCommentCount(publishId, 1);
            redisTemplate.opsForValue().set(key, String.valueOf(loveCount));
        } else {
            loveCount = redisTemplate.opsForValue().increment(key);
        }

        // 添加 用户对动态的喜欢记录
        String userKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.opsForValue().set(userKey, "1");

        return loveCount;
    }

    public Long unLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean removeComment = quanZiApi.removeComment(user.getId(), publishId, 3);
        if (!removeComment) {
            return null;
        }

        // 喜欢数减一,返回的是减一之后的喜欢数
        Long count = redisTemplate.opsForValue().decrement("QUANZI_COMMENT_LOVE_" + publishId);
        // 移除 用户对动态的喜欢记录
        redisTemplate.delete("QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId);

        return count;
    }

    public Movements queryById(String publishId) {
        Publish publish = quanZiApi.queryPublishById(publishId);
        List<Movements> movements = fillValueToMovements(Arrays.asList(publish));
        return movements.get(0);
    }

    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        String visitorKey = "visitor_date_" + user.getId();// redis 记录查询时间

        // 如果redis中存在上次查询的时间，就按照这个时间之后查询，如果没有就查询前5个
        List<Visitors> visitors = null;
        String value = this.redisTemplate.opsForValue().get(visitorKey);
        if(StringUtils.isEmpty(value)){
            visitors = this.visitorsApi.topVisitor(user.getId(), 5);
        }else{
            visitors = this.visitorsApi.topVisitor(user.getId(), Long.valueOf(value));
        }
        // 记录本次查询时间
//        redisTemplate.opsForValue().set(visitorKey,String.valueOf(System.currentTimeMillis()));

        // 如果没查到数据则返回空集合
        if (CollectionUtils.isEmpty(visitors)){
            return Collections.emptyList();
        }

        // 获取来访用户的id集合
        List<Long> ids = new ArrayList<>();
        for (Visitors visitor : visitors) {
            ids.add(visitor.getVisitorUserId());
        }

        // 查询mysql用户详细信息
        QueryWrapper<Visitors> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",ids);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);

        // 封装返回数据
        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (Visitors visitor : visitors) {
            for (UserInfo userInfo : userInfoList) {
                if (visitor.getVisitorUserId() == userInfo.getId()){
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVoList;
    }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);

        List<Publish> records = albumPageInfo.getRecords();

        if(CollectionUtils.isEmpty(records)){
            return pageResult;
        }

        pageResult.setItems(fillValueToMovements(records));

        return pageResult;

    }
}
